const appconfig = require('@/appconfig.js');
const fwlog = require('@/static/core/fwlog.js');

const fwtool = {
  //访问api
  requestApi: function(api, params, method, successcallback, failcallback, completecallback) {
    //导航显示加载图标
	uni.showLoading({
		title:'加载中...'
	});
	
    if (method == ''||null == method) {
      //GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
      method = 'POST';
    }
    
    //输出日志
    fwlog.debug(api);
    fwlog.debug(params);

    uni.request({
      url: api,
      data: params,
      header: {
        'content-type': 'application/x-www-form-urlencoded',
      },
      responseType: 'text',
      method: method,
      dataType: 'json',
      success: function(res) {
        //输出日志
        fwlog.debug(res.data);

        if (res.statusCode !== 200) {
          fwtool.showModalInfo('网络请求错误');
          return;
        }
        if (typeof res.data !== 'object') {
          fwtool.showModalInfo('响应数据错误');
          return;
        }
        //检测是否需要登录
        if (res.data.code == appconfig.fwcode.nologin) {
          // 登录态失效, 重新登录
          uni.showModal({
            title: '友情提示',
            content: '该帐号在其他设备登录！请重新登录',
            showCancel: true,
            cancelText: '暂不登录',
            confirmText: '马上登录',
            success: function(res) {
              if (res.confirm) {
                try {
                  uni.clearStorageSync();
                  uni.clearStorage();
                  uni.redirectTo({
                    url: '/pages/basic/login/index',
                  });
                } catch (e) {
                  fwlog.error(e);
                }
              } else if (res.cancel) {
                try {
                  uni.clearStorageSync();
                  uni.clearStorage();
                } catch (e) {
                  fwlog.error(e);
                }

                let pages = getCurrentPages();
                if (pages.length) {
                  let currentPage = pages[0];
                  uni.reLaunch({
                    url: '/' + currentPage.route,
                  });
                } else {
                  uni.reLaunch({
                    url: '/pages/index/index',
                  });
                }
              }
            }
          });
          return;
        }
        //执行成功回调
        successcallback && successcallback(res.data);
      },
      fail: function(res) {
        fwlog.error(res.errMsg);
        failcallback && failcallback(res);
      },
      complete: function(res) {
        //隐藏导航加载图标
        uni.hideLoading();
        completecallback && completecallback(res);
      }
    })
  },
  //信息弱提示
  showToastInfo: function(msg, mask, duration, successcallback, failcallback, completecallback) {
    if (null == duration || isNaN(duration) || duration == 0) {
      duration = 1500;
    }
    if (null == mask || typeof mask == 'undefined'){
      mask = false;
    }
    //uni.hideToast();

    uni.showToast({
      title: msg,
      icon: 'none',
      duration: duration,
      mask: mask,
      success: function(res) {
        successcallback && setTimeout(function() {
          successcallback(res)
        }, duration);
      },
      fail: function(res) {
        fwlog.error(res.errMsg);
        failcallback && failcallback(res);
      },
      complete: function(res) {
        completecallback && completecallback(res);
      }
    });
  },
  //信息弹框提示
  showModalInfo: function(msg, successcallback, failcallback, completecallback) {
    uni.showModal({
      title: '友情提示',
      content: msg,
      showCancel: false,
      success: function(res) {
        successcallback && successcallback(res);
      },
      fail: function(res) {
        fwlog.error(res.errMsg);
        failcallback && failcallback(res);
      },
      complete: function(res) {
        completecallback && completecallback(res);
      }
    });
  },
  //确认框提示
  showModalConfirm: function(title, msg, cancelText, confirmText, successcallback, failcallback, completecallback) {
    if (title == '') {
      title = '信息提示';
    }
    if (cancelText == '') {
      cancelText = '取消';
    }
    if (confirmText == '') {
      confirmText = '确定';
    }

    uni.showModal({
      title: title,
      content: msg,
      showCancel: true,
      cancelText: cancelText,
      confirmText: confirmText,
      success: function(res) {
        successcallback && successcallback(res.confirm, res.cancel);
      },
      fail: function(res) {
        fwlog.error(res.errMsg);
        failcallback && failcallback(res);
      },
      complete: function(res) {
        completecallback && completecallback(res);
      }
    });
  },
  //比较版本
  compareVersion: function(v1, v2) {
    v1 = v1.split('.')
    v2 = v2.split('.')
    const len = Math.max(v1.length, v2.length)

    while (v1.length < len) {
      v1.push('0')
    }
    while (v2.length < len) {
      v2.push('0')
    }

    for (let i = 0; i < len; i++) {
      const num1 = parseInt(v1[i])
      const num2 = parseInt(v2[i])

      if (num1 > num2) {
        return 1
      } else if (num1 < num2) {
        return -1
      }
    }

    return 0
  },
  //格式化url字符串
  encodeJsonStr: function (jsonParam) {
    return encodeURIComponent(JSON.stringify(jsonParam));
  },
  //解析url字符串
  decodeJsonStr: function (jsonStr) {
    return JSON.parse(decodeURIComponent(jsonStr));
  },
  //格式化url字符串
  encodeUrlJsonStr: function(webUrl) {
    let jsonParam = {
      url: webUrl
    };
    return encodeURIComponent(JSON.stringify(jsonParam));
  },
  //解析url字符串
  decodeUrlJsonStr: function(jsonParam) {
    let jsonParamObject = JSON.parse(decodeURIComponent(jsonParam));
    return jsonParamObject.url;
  },
  //设置自适应尺寸
  setAutoSize: function(callback) {
    //  高度自适应
    uni.getSystemInfo({
      success: function(res) {
        var clientHeight = res.windowHeight,
          clientWidth = res.windowWidth,
          rpxR = 750 / clientWidth;
        callback && callback({
          cwidth: 750,          
          rpxRate: rpxR,
          cheight: (clientHeight * rpxR),
          pixelRatio: res.pixelRatio
        }, res);
      }
    });
  },
  //兼容多页，期中首页未加载满当前页面，未触发onReachBottom事件
  loadPageMore: function (tidName, callback) {
    let _this = this;
    uni.getSystemInfo({
      success: function (res) {
        let winHeight = res.windowHeight;

        var query = uni.createSelectorQuery();
        query.select('#' + tidName).boundingClientRect();
        query.exec(function (qres) {
          if (qres[0].height < winHeight) {
            callback && callback();
          }
        });
      },
    });
  },
  //单页数据未满屏，自动加载第二页数据
  autoLoadMore: function(_this){
    if (1 == _this.data.dataPageNum && _this.data.dataPageTotal > 1) {
      fwtool.loadPageMore(_this.data.listContainerId, function () {
        _this.loadPageList(null);
      });
    }
  },
  //图片加载失败显示默认图
  //image中设置 binderror="bindImageError" data-index="0" data-src="/resources/image/empty/icon_empty_rectangle.png" data-variable="var" data-property="pro"
  bindImageError: function (eventhandle, _this) {
    let evthleDataset = eventhandle.currentTarget.dataset;
    let tmpIndex = evthleDataset.index;
    let tmpSrc = evthleDataset.src;
    let tmpVariable = evthleDataset.variable;
    let tmpProperty = evthleDataset.property;
    if (typeof tmpProperty == 'undefined'){
      if (typeof tmpIndex == 'undefined'){
        _this.setData({
          [tmpVariable]: tmpSrc
        });
      }else{
        _this.setData({
          [tmpVariable + '[' + tmpIndex+']']: tmpSrc
        });
      }
    }else{
      if (typeof tmpIndex == 'undefined') {
        _this.setData({
          [tmpVariable + '.' + tmpProperty]: tmpSrc
        });
      }else{
        _this.setData({
          [tmpVariable + '.' + tmpProperty + '[' + tmpIndex + ']']: tmpSrc
        });
      }
    }    
  },
  //列表图片加载失败显示默认图
  //image中设置 binderror="bindImageListError" data-index="{{index}}" data-src="/resources/image/empty/icon_empty_rectangle.png" data-variable="var" data-property="pro"
  bindImageListError: function (eventhandle, _this) {
    let evthleDataset = eventhandle.currentTarget.dataset;
    let tmpIndex = evthleDataset.index;
    let tmpSrc = evthleDataset.src;
    let tmpVariable = evthleDataset.variable;
    let tmpProperty = evthleDataset.property;
    if (typeof tmpProperty == 'undefined') {
      _this.setData({
        [tmpVariable + '[' + tmpIndex + ']']: tmpSrc
      });
    }else{
      _this.setData({
        [tmpVariable + '[' + tmpIndex + '].' + tmpProperty]: tmpSrc
      });
    }    
  },
  //列表嵌套列表图片加载失败显示默认图
  //image中设置 binderror="bindImageListToListError" data-index="{{index}}" data-index2="{{indexK}}" data-src="/resources/image/empty/icon_empty_rectangle.png" data-variable="var" data-property="pro"
  bindImageListToListError: function (eventhandle, _this) {
    let evthleDataset = eventhandle.currentTarget.dataset;
    let tmpIndex = evthleDataset.index;
    let tmpIndex2 = evthleDataset.index2;
    let tmpSrc = evthleDataset.src;
    let tmpVariable = evthleDataset.variable;
    let tmpProperty = evthleDataset.property;
    if (typeof tmpProperty == 'undefined') {
      _this.setData({
        [tmpVariable + '[' + tmpIndex + '][' + tmpIndex2+']']: tmpSrc
      });
    } else {
      _this.setData({
        [tmpVariable + '[' + tmpIndex + '].' + tmpProperty + '[' + tmpIndex2+']']: tmpSrc
      });
    }
  },
  // 返回上N页
  navigateBackPage:function(pageLayerNum,callback){
    let pages = getCurrentPages();
    let targetPage = pages[pages.length - 1 - pageLayerNum];
    // targetPage.route
    uni.navigateBack({
      delta: pageLayerNum,
      success:function(){
        callback && callback(targetPage);
      }
    });
  },
  // 打开下一页，预设路径用'|'分隔
  navigateNextPage: function (navPath,callback) {
    let currentPathIsLast = false;

    if (navPath.length > 0 && (navPath.indexOf('|') != -1)) {
      let pages = getCurrentPages();
      let currentPage = pages[pages.length - 1];
      let currentPathIndex = -1;
      let paths = navPath.split('|');
      
      for (let i = 0; i < paths.length; i++) {
        if(paths[i].indexOf('?') != -1){
          if (paths[i].substring(0,paths[i].indexOf('?')) == '/' + currentPage.route) {
            currentPathIndex = i;
            break;
          }
        }else{
          if (paths[i] == '/' + currentPage.route) {
            currentPathIndex = i;
            break;
          }
        }
      }

      if (currentPathIndex > -1 && (paths.length > currentPathIndex + 1)) {
        uni.navigateTo({
          url: paths[currentPathIndex + 1],
        })
      }else{
        currentPathIsLast = (paths.length <= (currentPathIndex+1));
      }
    }
    callback && callback(currentPathIsLast);
  }
}

module.exports = fwtool;